package com.example.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                      Authentication authentication) throws IOException, ServletException {
        String targetUrl = request.getParameter("redirect_uri");
        
        if (isAbsoluteUrl(targetUrl)) {
            // 返回JSON响应
            Map<String, Object> result = new HashMap<>();
            result.put("status", "success");
            result.put("message", "Authentication successful");
            
            if (authentication.getPrincipal() instanceof OidcUser) {
                OidcUser oidcUser = (OidcUser) authentication.getPrincipal();
                result.put("email", oidcUser.getEmail());
                result.put("name", oidcUser.getFullName());
                result.put("picture", oidcUser.getPicture());
            }
            
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter().write(objectMapper.writeValueAsString(result));
        } else {
            // 重定向到相对路径
            String redirectUrl = targetUrl != null ? targetUrl : "/";
            response.sendRedirect(redirectUrl);
        }
    }

    private boolean isAbsoluteUrl(String url) {
        if (url == null) {
            return false;
        }
        return url.startsWith("http://") || url.startsWith("https://");
    }
} 